package com.example.demo.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.HibernateValidator;

/**
 * hibernate-validator验证
 * @author 陈浩
 * @date 2021/1/22 16:57
 */
@Slf4j
public class ValidationUtil {

    /**
     * 开启快速结束模式 failFast (true)
     */
    private static Validator validator = Validation
            .byProvider(HibernateValidator.class)
            .configure()
            .failFast(false)
            .buildValidatorFactory()
            .getValidator();

    public static <T> void validateBean(T t, Class<?>...groups) throws Exception {
        Set<ConstraintViolation<T>> violationSet = validator.validate(t, groups);
        boolean hasError = violationSet != null && violationSet.size() > 0;

        if (hasError) {
            ConstraintViolation<T> tConstraintViolation = violationSet.stream().findFirst().get();
            throw new Exception(tConstraintViolation.getMessage());

        }

    }


}
